package com.qs.rocketmq.order.controller;


import com.qs.rocketmq.common.base.BaseController;
import com.qs.rocketmq.order.util.OrderConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQLocalRequestCallback;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class MsgSendController extends BaseController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送顺序消息
     * <p>
     * 这种方式发送消息，消息按照顺序发送，消费端消费消息后，不会发送应答回执。
     *
     * @author qinyupeng
     * @since 2022-07-01 01:37:30
     */
    @GetMapping(value = "/sendOrderMsg")
    public String sendOrderMsg() {
        String destination = OrderConstant.ORDER_APP_TOPIC + ":" + OrderConstant.ORDER_APP_TAG_TEST;
        // 同步发送顺序消息，hashKey参数用来标识这个参数，在业务上可以为 orderId、productId等，将这些消息发送到同一个队列中
        rocketMQTemplate.syncSendOrderly(destination, "修改订单1", "0001");
        rocketMQTemplate.syncSendOrderly(destination, "修改订单2", "0002");
        rocketMQTemplate.syncSendOrderly(destination, "修改订单3", "0003");
        return "顺序消息发送成功";
    }


    /**
     * 同步发送应答
     *
     * @author qinyupeng
     * @since 2022-07-01 01:52:42
     */
    @GetMapping(value = "/sendSyncMsg")
    public String sendSyncMsg() {
        String destination = OrderConstant.ORDER_APP_TOPIC + ":" + OrderConstant.ORDER_APP_TAG_TEST;
        String msgContent = "这个是消息内容，测试同步发送消息";
        Message<String> message = MessageBuilder.withPayload(msgContent).setHeader("KEYS", "A").build();
        String sendResult = rocketMQTemplate.sendAndReceive(destination, message, String.class);
        log.info("发送端收到消费端返回的内容：sendResult={}", sendResult);
        return "ok";
    }


    /**
     * 异步发送应答
     *
     * @author qinyupeng
     * @since 2022-07-01 01:52:18
     */
    @GetMapping(value = "/sendAsyncMsg")
    public String sendAsyncMsg() {
        String destination = OrderConstant.ORDER_APP_TOPIC + ":" + OrderConstant.ORDER_APP_TAG_TEST;
        String msgContent = "这个是消息内容，测试异步发送消息";
        Message<String> message = MessageBuilder.withPayload(msgContent).setHeader("category", "电器").build();
        rocketMQTemplate.sendAndReceive(destination, message, new RocketMQLocalRequestCallback<String>() {
            @Override
            public void onSuccess(String result) {
                log.info("消息发送和消费成功，返回结果：result={}", result);
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("异步消息发送失败");
                throwable.printStackTrace();
            }
        }, 5000);

        return "ok";
    }
}
